package controlSoftware.DataIn;

import java.io.IOException;
import java.util.Queue;
import java.util.logging.FileHandler;
import java.util.logging.Logger;

import controlSoftware.util.DataFormatter;
import controlSoftware.util.RecordHandler;
import controlSoftware.DataProcess.SensorData;
import controlSoftware.DataProcess.SysModel;
import controlSoftware.GUI.mainUI;
import controlSoftware.MockDataIn.MockDataSource;

public class DataIn extends Thread {
	int id;
	String threadName;
	String ip = "";
	int port = 0;
	String filePath = "";
	Queue<SensorData> userData = null;
	SensorData data = null;
	private RecordHandler recordManager;
	String readings;
	String[] tokens;
	public TelnetParser telnet;

	/**
	 * data in thread constructed with telnet connection
	 * 
	 * @param threadName
	 * @param userData
	 * @param ip
	 * @param port
	 * @param record
	 */
	public DataIn(int id, String threadName, Queue<SensorData> userData,
			String ip, int port, RecordHandler record) {
		this.userData = userData;
		this.threadName = threadName;
		this.ip = ip;
		this.port = port;
		this.recordManager = record;
	}

	/**
	 * data in thread constructed with mock data source
	 * 
	 * @param threadName
	 * @param userData
	 * @param filePath
	 */
	public DataIn(int id, String threadName, Queue<SensorData> userData,
			String filePath) {
		this.id = id;
		this.userData = userData;
		this.threadName = threadName;
		this.filePath = filePath;
		this.recordManager = null;
	}

	public String getThreadName() {
		return threadName;
	}

	@Override
	/**
	 * data in thread execution statement
	 */
	public void run() {
		// declare mock data source: static or from file
		MockDataSource mockDataSource = null;
		telnet = null;

		if (mainUI.usingMockDataFlag) {
			mockDataSource = new MockDataSource(filePath);
		} else {
			// initialize Telnet Parser
			telnet = new TelnetParser(ip, port, recordManager);

			System.out.println("Waiting on Telnet Connection...");
			mainUI.statusBar.setText("Device " + id + ": Waiting on Telnet Connection...");
			while ((telnet.connect()) != true) {
			}
			System.out.println("Telnet connection established.");
		}

		while (!this.isInterrupted()) {
			if (mainUI.usingMockDataFlag) {
				// test with mock data
				data = mockDataSource.getNextMockData();

				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
				}

				if (data != null) {
					userData.add(data);
				}
			} else {// telnet data transaction
				try {
					readings = telnet.getReadings();
				} catch (Exception conn) {

				}

				if (readings != null) {
					tokens = readings.split("\\r\\n");

					for (String token : tokens) {
						String[] dataString = token.split("\\,");

						// discard if data is partial
						if (dataString.length != 4) {
							data = null;
						} else {
							try {
								if(mainUI.isPaused){
									mainUI.pausedTime = Long.parseLong(dataString[0]);
									data = new SensorData(
											-1,
											Double.parseDouble(dataString[1]),
											Double.parseDouble(dataString[2]),
											Double.parseDouble(dataString[3]),
											0, 0, 0);
								}
								else if (mainUI.isXaxisDisabled) {
									data = new SensorData(
											Long.parseLong(dataString[0]),
											0,
											Double.parseDouble(dataString[2]),
											Double.parseDouble(dataString[3]),
											0, 0, 0);
									
								} else if (mainUI.isYaxisDisabled) {
									data = new SensorData(
											Long.parseLong(dataString[0]),
											Double.parseDouble(dataString[1]),
											0,
											Double.parseDouble(dataString[3]),
											0, 0, 0);
								} else {
									data = new SensorData(
											Long.parseLong(dataString[0]),
											Double.parseDouble(dataString[1]),
											Double.parseDouble(dataString[2]),
											Double.parseDouble(dataString[3]),
											0, 0, 0);
								}
							} catch (Exception e) {
								// handle any parsing error
								System.out.println(e.getMessage());
								System.out
										.println("Corrupted data recevied; data is dropped.");
								mainUI.statusBar.setText("Device " + id + ": dropped corrupted data");

								data = null;
							}
						}

						if (data != null && data.getTimeStamp() != -1) {
							if (mainUI.isRecording) {
								try {
									this.recordManager.out.write(data
											.getTimeStamp()
											+ ","
											+ data.getAccel_x()
											+ ","
											+ data.getAccel_y()
											+ ","
											+ data.getAccel_z() + ",0,0,0\r\n");
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
							
							System.out.println(data.getTimeStamp() + ","
									+ data.getAccel_x() + ","
									+ data.getAccel_y() + ","
									+ data.getAccel_z());
							
							userData.add(data);
						}
					}
				}
			}
		}
	}

	public RecordHandler getRecordManager() {
		return recordManager;
	}

	public void setRecordManager(RecordHandler recordManager) {
		this.recordManager = recordManager;
	}
}
